

class TimerCallback {

    constructor(public func: Function, public now: number, public time: number, public once: boolean) {
        this.now += time;

    }

    addNextTime() {
        this.now += this.time;
    }
}

class Timer {
    callbacks: TimerCallback[] = []

    addCallback(callback: TimerCallback) {
        return this.callbacks.push(callback) - 1;
    }

    checkCall(time: number) {

        for (const key in this.callbacks) {
            let callback = this.callbacks[key];
            if (callback?.now < time) {
                callback.func();
                if (callback.once) {
                    this.callbacks[key] = undefined;
                } else {
                    callback.addNextTime();
                }
            }
        }

        this.callbacks = this.callbacks.filter(c => c)

    }


}

export const timer = new Timer()

globalThis.__Update__ = () => {
    timer.checkCall(Date.now())
}

globalThis.setTimeout = (func: Function, time: number) => {

    let callback = new TimerCallback(func, Date.now(), time, true);
    timer.addCallback(callback);

}

globalThis.setInterval = (func: Function, time: number) => {

    let callback = new TimerCallback(func, Date.now(), time, false);
    timer.addCallback(callback);

}




